/**
 * moonlight Web开发 基础服务.
 * Copyright 2000-2020 ALPHA LAB.Inc
 * author:allen
 * date:2018-2-23
 */
define(["jquery"], function ($) {
	
	//定义远程服务方法
	var RemoteService = {};
	RemoteService.doPost = function(serviceName, methodName, parameters){
		var resultDatas = null;
		var REMOTE_SERVLET = getContextPath()+"/remoteService/handleRequest";
		//需将参数数组，即json对象转成json字符串
		var paramData = {"serviceName": serviceName, "methodName":methodName, "parameters": JSON.stringify(parameters)};
		$.ajax({   
			url: REMOTE_SERVLET,
			type:"POST",   
			//设置为同步，这样返回的resultDatas就能被success回调函数赋值
			async:false,
			data:paramData,
			//用以下配置可兼容post和get方法
			contentType: "application/x-www-form-urlencoded;charset=UTF-8",
			success: function (result) {
				if(result.data && typeof result.data == "object" && !Array.isArray(result.data)){
					var rstData = result.data;
					//如果result是一个对象，判断其是否持有动态属性，有则加到新对象中
					if(rstData.dynamicMap){
						resultDatas = result;
						var dynData = rstData;
						for(var key in rstData.dynamicMap){
							dynData[key]=rstData.dynamicMap[key];
						}
						resultDatas.data = dynData;
					}else{
						resultDatas = result;
					} 
				}else if(result.list && Array.isArray(result.list)){
					var rstList = result.list;
					//如果result是一个集合，则进行判断是否持有动态属性，有则加到新结果集中
					resultDatas = result;
					var dynList = [];
					$.each(rstList, function(index,item){ 
						if(item.dynamicMap){
							var itemData = item;
							for(var key in item.dynamicMap){
								itemData[key]=item.dynamicMap[key];
							} 
							dynList.push(itemData);
						}else{
							dynList.push(item);
						}
					});
					resultDatas.list = dynList;
				}else{
					resultDatas = result;
				} 
			}, 
			error: function() {
				console.log('服务器端有错！');
			}		
		});	
		return resultDatas; 
	};	
	
	//获取项目根目录路径，即项目名
	function getContextPath(){
		var contextPath = document.location.pathname; 
		var index =contextPath.substr(1).indexOf("/"); 
		contextPath = contextPath.substr(0,index+1); 
		delete index; 
		return contextPath;   		
	}
	
	var service = {
		RemoteService:RemoteService	
	};
	return service;
	
});